package com.example.zzx.dovebook.personalcenter.follow.follower

import android.graphics.Color
import android.os.Bundle
import android.text.TextUtils
import android.view.MenuItem
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import com.example.baselibrary.widget.LoadingStateView
import com.example.library.BaseAdapter
import com.example.zzx.dovebook.R
import com.example.zzx.dovebook.base.BaseActivity
import com.example.zzx.dovebook.base.ValueWrapper
import com.example.zzx.dovebook.personalcenter.follow.UserFollow
import com.example.zzx.dovebook.user.UserManager
import kotlinx.android.synthetic.main.activity_follower.*
import kotlinx.android.synthetic.main.toolbar_common.*

class FollowerActivity: BaseActivity<FollowerViewModel>() {

    private lateinit var adapter: BaseAdapter
    private lateinit var emptyView: LoadingStateView
    private lateinit var loadMoreView: LoadingStateView

    private lateinit var userId: String
    private lateinit var userName: String

    private var lastItemCreateAt = System.currentTimeMillis()

    override fun getLayoutId(): Int {
        return R.layout.activity_follower
    }

    override fun createRepository(): Any {
        return FollowerRepository()
    }

    override fun createViewModel(): Class<FollowerViewModel> {
        return FollowerViewModel::class.java
    }

    override fun initViews(savedInstanceState: Bundle?) {
        setupToolbar()

        setupRecycler()
    }

    override fun initIntent(savedInstanceState: Bundle?) {
        userId = intent.getStringExtra(getString(R.string.user_id_arg_name))
        userName = intent.getStringExtra(getString(R.string.user_name_arg_name))
    }

    override fun initOptions(savedInstanceState: Bundle?) {
        queryFollowers()
    }

    private fun queryFollowers() {
        adapter.lastItem?.let {
            lastItemCreateAt = (it as UserFollow).createAt
        }
        val userId = UserManager.getInstance(this).loginUserId ?: ""
        viewModel.queryFollowers(userId, lastItemCreateAt).observe(this, Observer {
            it!!.value ?: run {
                if (adapter.dataCount > 0) {
                    when (it.type) {
                        ValueWrapper.TYPE_FAILED -> loadMoreView.failed()
                        ValueWrapper.TYPE_NO_CONTENT -> loadMoreView.noMore()
                    }
                } else {
                    when (it.type) {
                        ValueWrapper.TYPE_FAILED -> emptyView.failed()
                        ValueWrapper.TYPE_NO_CONTENT -> emptyView.empty()
                    }
                }
                return@Observer
            }
            emptyView.success()
            if (adapter.isInEmptyState) adapter.cancelEmptyState()
            val myRequestList = it.value as List<UserFollow>
            if (myRequestList.size < 20) {
                loadMoreView.noMore()
            }
            adapter.add(myRequestList)
        })
    }

    fun follow(userFollow: UserFollow) {
        val fromUserId = UserManager.getInstance(this).loginUserId ?: ""
        viewModel.follow(fromUserId, userFollow.userId).observe(this, Observer {
            userFollow.followStatus = it!!
            userFollow.updateOperationView(this)
        })
    }

    fun cancelFollow(userFollow: UserFollow) {
        val fromUserId = UserManager.getInstance(this).loginUserId ?: ""
        viewModel.cancelFollow(fromUserId, userFollow.userId).observe(this, Observer {
            userFollow.followStatus = it!!
            userFollow.updateOperationView(this)
        })
    }

    private fun setupRecycler() {
        emptyView = LoadingStateView(this)
        emptyView.setTextColor(ContextCompat.getColor(this, R.color.support_text))
        emptyView.setOnRetryListener {
            emptyView.loading()
            queryFollowers()
        }
        loadMoreView = LoadingStateView(this)
        loadMoreView.setTextColor(Color.TRANSPARENT)
        loadMoreView.setOnRetryListener {
            loadMoreView.loading()
            queryFollowers()
        }
        adapter = BaseAdapter.Builder().emptyView(emptyView).addRooter(loadMoreView).build()
        adapter.emptyState()
        adapter.setOnLoadMoreListener {
            if (loadMoreView.isNoMore) {
                return@setOnLoadMoreListener
            }
        }
        recycler.adapter = adapter
    }

    private fun setupToolbar() {
        setSupportActionBar(toolbar)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        supportActionBar?.title = "${userName}的粉丝"
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        when (item?.itemId) {
            android.R.id.home -> finish()
        }
        return super.onOptionsItemSelected(item)
    }

    fun isLoginUser(): Boolean {
        return TextUtils.equals(UserManager.getInstance(this).loginUserId, userId)
    }

}